package com.bieber.smartpost.invoke.filter.filler;

import com.bieber.smartpost.httpcore.Cookie;
import com.bieber.smartpost.invoke.CookieContainer;
import com.bieber.smartpost.invoke.Filter;
import com.bieber.smartpost.invoke.FilterContext;
import com.jbeer.framework.annotation.Bean;
import com.jbeer.framework.exception.JBeerException;

import java.io.IOException;
import java.net.HttpCookie;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 从上一个请求返回的cookie里面取值
 * #{cookie:'xxxx'[cookies:xxxx][default:xxxx]}
 * Created by bieber on 14-11-30.
 */
@Bean
public class CookieFiller extends BasicFiller<Collection<HttpCookie>> {

    private static final String EXPRESSION_REGEX="'[\\w-]+'";

    private static final Pattern COOKIES_PATTERN = Pattern.compile("#\\{cookie:"+EXPRESSION_REGEX+DEFAULT_VALUE_REGEX+"\\}");

    @Override
    protected String getExpressionRegex() {
        return EXPRESSION_REGEX;
    }

    @Override
    protected String convertValue(String originValue, Collection<HttpCookie> cookies) throws JBeerException {
        List<FillerRule> rules = generateFillerRule(COOKIES_PATTERN,originValue);
        if(rules.size()<=0||cookies==null||cookies.size()<=0){
            return originValue;
        }
        String[] args = new String[rules.size()];
        for(int i=0;i<rules.size();i++){
            FillerRule rule = rules.get(i);
            args[i]=getCookieValue(cookies,rule.getExpression());
        }
        originValue = COOKIES_PATTERN.matcher(originValue).replaceAll("%s");
        return String.format(originValue,args);
    }

    private String getCookieValue(Collection<HttpCookie> cookies,String expression){
        for(HttpCookie cookie:cookies){
            if(cookie.getName().equalsIgnoreCase(expression)){
                return cookie.getValue();
            }
        }
        return "";
    }

    @Override
    protected Collection<HttpCookie> generateDataSource(FilterContext context) throws IOException, JBeerException {
        return CookieContainer.getCookies(context.getInvokeTask().getInvokeId());
    }
}
